package com.yixing.demo.component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yixing.demo.constants.Constants;
import com.yixing.demo.mapper.MessageMapper;
import com.yixing.demo.mapper.MessageSessionMapper;
import com.yixing.demo.model.Friend;
import com.yixing.demo.model.Request;
import com.yixing.demo.model.Response;
import com.yixing.demo.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class WebSocketClass extends TextWebSocketHandler {
    @Resource
    UserOnlineStatus userOnlineStatus;
    @Resource
    ObjectMapper objectMapper;
    @Resource
    MessageSessionMapper messageSessionMapper;

    @Resource
    MessageMapper messageMapper;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
       User userInfo = (User)session.getAttributes().get(Constants.USER_SESSION);
       if(userInfo == null) {
           log.info("获取不到user对象");
           return;
       }
       if(!userOnlineStatus.online(userInfo.getUserId(), session)) {
           session.sendMessage(new TextMessage("{\"action\":\"redirect\"}"));//json一定要加{}
       }
    }


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        User userInfo = (User)session.getAttributes().get(Constants.USER_SESSION);
        if(userInfo == null) {
            log.info("获取不到user对象");
            return;
        }
        Request request = objectMapper.readValue(message.getPayload(), Request.class);
        transmissionInformation(userInfo, request);
    }

    private void transmissionInformation(User userInfo, Request request) throws IOException {
         Response response = new Response();
         response.setFromId(userInfo.getUserId());
         response.setFromName(userInfo.getUsername());
         response.setSessionId(request.getSessionId());
         response.setContent(request.getContent());

        String respJson = objectMapper.writeValueAsString(response);
        List<Friend> friends = messageSessionMapper.getSessionFriendsBySessionId(request.getSessionId(), userInfo.getUserId());
        Friend myself = new Friend();
        myself.setFriendId(userInfo.getUserId());
        myself.setFriendName(userInfo.getUsername());
        friends.add(myself);

        for (Friend friend : friends) {
            WebSocketSession session = userOnlineStatus.getWebSocketSessionByUserId(friend.getFriendId());
            if(session == null) {
                continue;
            }else {
                session.sendMessage(new TextMessage(respJson));
            }
        }

        messageMapper.addMessage(userInfo.getUserId(), request.getSessionId(), request.getContent());
    }


    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        User userInfo = (User)session.getAttributes().get(Constants.USER_SESSION);
        if(userInfo == null) {
            log.info("获取不到user对象");
            return;
        }
        userOnlineStatus.offline(userInfo.getUserId(), session);
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        User userInfo = (User)session.getAttributes().get(Constants.USER_SESSION);
        if(userInfo == null) {
            log.info("获取不到user对象");
            return;
        }
        userOnlineStatus.offline(userInfo.getUserId(), session);
    }
}
